package com.mjgy.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.common.utils.R;
import com.mjgy.entity.BroadCastEntity;
import com.mjgy.entity.BroadCastLikerEntity;
import com.mjgy.entity.BroadCastSignerEntity;
import com.mjgy.entity.ContactWayWhiteList;
import com.mjgy.entity.MUserEntity;
import com.mjgy.entity.MessageEntity;
import com.mjgy.repository.BroadCastLikerRepository;
import com.mjgy.repository.BroadCastRepository;
import com.mjgy.repository.BroadCastSignerRepository;
import com.mjgy.repository.ContactWayWhiteListRepository;
import com.mjgy.repository.MUserRepository;
import com.mjgy.repository.MessageRepository;
import com.mjgy.service.BroadCastService;

/**
* @Description: TODO
* @author quanlq
* @date 2018年9月14日
* @version V1.0
*/
@RestController
@RequestMapping("/broadCast")
public class BroadCastController {
	
	@Autowired
	private BroadCastService broadCastService;
	@Autowired
	private BroadCastRepository broadCastRepository;
	@Autowired
	private BroadCastSignerRepository broadCastSignerRepository;
	@Autowired
	private BroadCastLikerRepository broadCastLikerRepository;
	@Autowired
	private MUserRepository mUserRepository;
	@Autowired
	private MessageRepository messageRepository;
	@Autowired
	private ContactWayWhiteListRepository contactWayWhiteListRepository;
	
	/**
	 * 发布约会广播
	 * 
	 * @param broadCastEntity 约会广播实体
	 * @return
	 */
	@RequestMapping(value = "/saveBroadCast", method = RequestMethod.POST)
	public R saveBroadCast(BroadCastEntity broadCastEntity){
		if(broadCastEntity == null){
			return R.error();
		}
		DateFormat dFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //HH表示24小时制；  
        String currentTime = dFormat.format(new Date());  
        
		broadCastEntity.setCreateTime(currentTime);
		broadCastEntity.setLikeNum(0);
		broadCastEntity.setSignNum(0);
		broadCastEntity.setIsDeleted(0);
		broadCastService.saveBroadCast(broadCastEntity);
		return R.success();
	}
	
	/**
	 * 查询广播列表（带分页）
	 * 
	 * @param sortKey	排序关键字
	 * @param sex	性别
	 * @param city	城市
	 * @param userId	用户ID
	 * @param page	页码
	 * @param size	每页条数
	 * @return
	 */
	@RequestMapping(value = "/findList")
	public R findList(String sortKey, Integer sex, String city, Long userId, Integer page, Integer size) {
		if(page == null){
			page = 1;
		}
		if(size == null){
			size = 20;
		}
		List<Map<String, Object>> list = broadCastService.findList(sortKey, sex, city, userId, page, size);
		return R.success().put("data", list);
	}
	
	/**
	 * 点赞约会广播
	 * 
	 * @param broadCastLikerEntity 点赞约会广播实体
	 * @return
	 */
	@RequestMapping(value = "/like", method = RequestMethod.POST)
	public R like(BroadCastLikerEntity broadCastLikerEntity){
		if(broadCastLikerEntity == null){
			return R.error(202, "入参不能诶空");
		}else if(broadCastLikerEntity.getBroadCastId() == null){
			return R.error(202, "广播ID不能为空");
		}else if(broadCastLikerEntity.getLikerId() == null){
			return R.error(202, "点赞人ID不能为空");
		}
		
		Integer count = broadCastLikerRepository.countByBroadCastIdAndLikerId(broadCastLikerEntity.getBroadCastId(), 
				broadCastLikerEntity.getLikerId());
		if(count > 0){
			return R.error(202, "你已经点赞该广播，请不要重复点赞");
		}
		broadCastService.like(broadCastLikerEntity);
		return R.success();
	}
	
	/**
	 * 报名约会广播
	 * 
	 * @param broadCastSignerEntity 报名约会广播实体
	 * @return
	 */
	@RequestMapping(value = "/signUp", method = RequestMethod.POST)
	public R signUp(BroadCastSignerEntity broadCastSignerEntity){
		if(broadCastSignerEntity == null){
			return R.error(202, "入参不能为空");
		}else if(broadCastSignerEntity.getBroadCastId() == null){
			return R.error(202, "广播ID不能为空");
		}else if(broadCastSignerEntity.getSignerId() == null){
			return R.error(202, "报名人ID不能为空");
		}
		Integer count = broadCastSignerRepository.countByBroadCastIdAndSignerId(broadCastSignerEntity.getBroadCastId(),
				broadCastSignerEntity.getSignerId());
		if(count > 0){
			return R.error(202, "你已经报名该广播，请不要重复报名");
		}
		
		Integer countDated = broadCastSignerRepository.countByBroadCastIdAndSignerIdAndIsDated(
				broadCastSignerEntity.getBroadCastId(), broadCastSignerEntity.getSignerId(), 1);
		if(countDated > 1){
			return R.error(201, "该广播已在约会中，请勿报名");
		}
		
		broadCastSignerEntity.setIsDated(0);
		broadCastSignerEntity.setIsChecked(0);
		broadCastSignerEntity.setCreateTime(new Date());
		broadCastService.signUp(broadCastSignerEntity);
		return R.success();
	}
	
	/**
	 * 查看报名列表
	 * 
	 * @param broadCastId 约会广播ID
	 * @param page	页码
	 * @param size	每页条数
	 * @return
	 */
	@RequestMapping("/findSignerList")
	public R findSignerList(Long broadCastId, Integer page, Integer size) {
		if(page == null){
			page = 1;
		}
		if(size == null){
			size = 20;
		}
		page = (page - 1) * size;
		List<Map<String, Object>> list = broadCastService.findSignerList(broadCastId, page, size);
		return R.success().put("data", list);
	}
	
	/**
	 * 删除我的约会广播
	 */
	@RequestMapping(value = "/deleteMyBroadCast/{userId}", method = RequestMethod.DELETE)
	public R deleteMyBroadCast(@PathVariable Long userId){
		if(userId == null){
			return R.error(202, "userId不能为空");
		}
		
		broadCastService.updateStatus(1, userId);
		return R.success();
	}
	
	/**
	 * 查看用户的约会广播
	 * 
	 * @return
	 */
	@RequestMapping("/findByUserId")
	public R findByUserId(Long userId, Long viewerId){
		Map<String, Object> broadCastEntity = broadCastService.findByUserId(userId, viewerId);
		return R.success().put("data", broadCastEntity);
	}
	
	/**
	 * 报名列表->约他
	 * @param userId	发布广播的人ID
	 * @param signerId	报名人ID
	 * @return
	 */
	@RequestMapping(value = "/dateSomeone", method = RequestMethod.POST)
	public R dateSomeone(Long userId, Long signerId){
		if(userId == null){
			return R.error(202, "发广播的人ID不能为空");
		}
		if(signerId == null){
			return R.error(202, "报名人ID不能为空");
		}
		BroadCastEntity broadCastEntity = broadCastRepository.findTopByUserId(userId);
		Long broadCastId = broadCastEntity.getId();
		
		BroadCastSignerEntity broadCastSignerEntity = 
				broadCastSignerRepository.findTopByBroadCastIdAndSignerId(broadCastId, signerId);
		broadCastSignerEntity.setIsDated(1); //将被约人的报名状态设为被约
		broadCastSignerRepository.save(broadCastSignerEntity);
		
		//给双方发广播消息
		MUserEntity user = mUserRepository.findOne(userId);
		MUserEntity signer = mUserRepository.findOne(signerId);
		
		MessageEntity userMessage = new MessageEntity(); //发送给发布广播的人的消息
		userMessage.setIsChecked(0);
		userMessage.setSendTime(new Date());
		userMessage.setType("1");	//系统消息
		userMessage.setUserId(userId);
		
		MessageEntity signerMessage = new MessageEntity();	//发送给被约的报名人的消息
		signerMessage.setIsChecked(0);
		signerMessage.setSendTime(new Date());
		signerMessage.setType("1");
		signerMessage.setUserId(signerId);
		
		Long checkerId = userId; //查看联系方式的人的ID
		Long passiverId = signerId; //被查看联系方式的人的ID
		Integer type = 0;
		if(user.getSex() == 0){	//男士
			userMessage.setContent("你与 " + signer.getNickname() + " 配对成功，你可免费联系她");
			signerMessage.setContent("你与 " + user.getNickname() + " 配对成功，请留意微信或QQ");
			if(user.getIdentity() == 1){ //男士会员
				Integer count = contactWayWhiteListRepository.countByCheckerIdAndType(checkerId, 1);
				if(count < 3){
					type = 1;
				}
			}
		}else if(user.getSex() == 1){	//女士
			userMessage.setContent("你与 " + signer.getNickname() + " 配对成功，请留意微信或QQ"); 			
			signerMessage.setContent("你与 " + user.getNickname() + " 配对成功，你可免费联系她");
			checkerId = signerId;
			passiverId = userId;
			if(signer.getIdentity() == 1){
				Integer count = contactWayWhiteListRepository.countByCheckerIdAndType(checkerId, 1);
				if(count < 3){
					type = 1;
				}
			}
		}
		messageRepository.save(userMessage);
		messageRepository.save(signerMessage);
		
		//赋予男士免费查看女士联系方式权限（如果该男士没有查看女士联系方式的权限）
		Integer count = contactWayWhiteListRepository.countByUserIdAndCheckerId(passiverId, checkerId);
		if(count <= 0){
			ContactWayWhiteList contactWayWhiteList = new ContactWayWhiteList();
			contactWayWhiteList.setCheckerId(checkerId);
			contactWayWhiteList.setUserId(passiverId);
			contactWayWhiteList.setType(type);
			contactWayWhiteList.setCreateTime(new Date());
			contactWayWhiteListRepository.save(contactWayWhiteList);
		}
		
		return R.success();
	}
	
	/**
	 * 未读报名人总数
	 * @param broadCastId 广播ID
	 * @return
	 */
	@RequestMapping("/uncheckedSignerNum")
	public R uncheckedSignerNum(Long userId){
		if(userId == null){
			return R.error(202, "用户ID不能为空");
		}
		BroadCastEntity broadCastEntity = broadCastRepository.findTopByUserId(userId);
		if(broadCastEntity == null){
			return R.error(202, "该用户未发布广播");
		}
		
		Integer count = broadCastSignerRepository.countByBroadCastIdAndIsChecked(broadCastEntity.getId(), 0);
		return R.success().put("uncheckedSignerNum", count);
	}
	
	/**
	 * 判断两人是否约会过
	 * @param activeId 主动方ID
	 * @param passiveId 被动方ID
	 * @return
	 */
	@RequestMapping("/isDated")
	public R isDated(Long activeId, Long passiveId){
		Integer count = broadCastSignerRepository.isDated(activeId, passiveId);
		return R.success().put("isDated", count > 0);
	}
	
	
	//------------------------------- 管理后台接口  ---------------------------------------------------------//
	
	/**
	 * 根据性别查询约会广播列表
	 * 
	 * @param sex	性别
	 * @param page	页码
	 * @param size	每页条数
	 * @return
	 */
	@RequestMapping(value = "/findListBySex/{sex}")
	public R findListBySex(@PathVariable Integer sex, String nickname, Integer page, Integer size){
		if(page == null){
			page = 1;
		}
		if(size == null){
			size = 20;
		}
		if(nickname == null){
			nickname = "";
		}
		List<Map<String, Object>> list = broadCastService.findListBySex(sex, nickname, page, size);
		Long totalCount = broadCastService.countBySex(sex, nickname);
		Long totalPage = totalCount / size + (totalCount % size == 0?0:1);
		
		Map<String, Object> data = new HashMap<>();
		data.put("list", list);
		data.put("currPage", page);
		data.put("pageSize", size);
		data.put("totalCount", totalCount);
		data.put("totalPage", totalPage);
		return R.success().put("data", data);
	}
	
	/**
	 * 根据ID查看约会广播详情
	 * 
	 * @param broadCastId 约会广播ID
	 * @return
	 */
	@RequestMapping(value = "/findById/{broadCastId}")
	public R findById(@PathVariable Long broadCastId){
		Map<String, Object> broadCastDetail = broadCastService.findById(broadCastId);
		return R.success().put("data", broadCastDetail);
	}
	
	/**
	 * 删除用户的约会广播（管理员删除）
	 * 
	 * @param userId 用户ID
	 * @return
	 */
	@RequestMapping(value = "/deleteByAdmin/{userId}", method = RequestMethod.DELETE)
	public R deleteByAdmin(@PathVariable Long userId){
		broadCastService.updateStatus(2, userId);
		return R.success();
	}
	
	/**
	 * 封禁广播图片
	 * @param broadCastId	广播ID
	 * @param forbidImages	封禁图片
	 * @return
	 */
	@RequestMapping(value = "/forbidImages")
	public R forbidImages(Long broadCastId, String forbidImages){
		if(broadCastId == null){
			return R.error(202, "广播ID不能为空");
		}
		
		BroadCastEntity broadCastEntity = broadCastRepository.findOne(broadCastId);
		if(broadCastEntity == null){
			return R.error(202, "该广播不存在");
		}
		
		broadCastEntity.setForbidImages(forbidImages);
		broadCastRepository.save(broadCastEntity);
		return R.success();
	}
	
}
